import UIKit

/// 页面A - 接收Flutter传递的用户信息
class PageAViewController: UIViewController {

    var userInfo: [String: Any] = [:]


    private let userInfoLabel = UILabel()
    private let openPageBButton = UIButton(type: .system)
    private let closeButton = UIButton(type: .system)

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        displayUserInfo()
    }

    private func setupUI() {
        // Use compatible background color for iOS versions before 13.0
        if #available(iOS 13.0, *) {
            view.backgroundColor = .systemBackground
        } else {
            view.backgroundColor = .white
        }
        title = "iOS原生页面A"

        // 设置自定义返回按钮 - 使用项目中的 ic_back 图片
        let backButton = UIButton(type: .custom)
        if let backImage = UIImage(named: "ic_back") {
            backButton.setImage(backImage, for: .normal)
        } else {
            // 如果没有找到图片，使用系统返回箭头
            if #available(iOS 13.0, *) {
                backButton.setImage(UIImage(systemName: "chevron.left"), for: .normal)
            } else {
                // Fallback on earlier versions
            }
        }
        backButton.tintColor = .systemBlue
        backButton.addTarget(self, action: #selector(backButtonTapped), for: .touchUpInside)

        // 设置按钮大小
        backButton.frame = CGRect(x: 0, y: 0, width: 44, height: 44)
        backButton.contentEdgeInsets = UIEdgeInsets(top: 0, left: -10, bottom: 0, right: 10)

        navigationItem.leftBarButtonItem = UIBarButtonItem(customView: backButton)

        // 用户信息显示标签
        userInfoLabel.numberOfLines = 0
        userInfoLabel.textAlignment = .center
        userInfoLabel.font = .systemFont(ofSize: 16)
        userInfoLabel.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(userInfoLabel)

        // 打开页面B按钮
        openPageBButton.setTitle("打开页面B", for: .normal)
        if #available(iOS 13.0, *) {
            openPageBButton.backgroundColor = .systemBlue
        } else {
            openPageBButton.backgroundColor = UIColor(red: 0.0, green: 122.0/255.0, blue: 1.0, alpha: 1.0)
        }
        openPageBButton.setTitleColor(.white, for: .normal)
        openPageBButton.layer.cornerRadius = 8
        openPageBButton.addTarget(self, action: #selector(openPageBButtonTapped), for: .touchUpInside)
        openPageBButton.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(openPageBButton)

        // 关闭按钮
        closeButton.setTitle("关闭页面", for: .normal)
        if #available(iOS 13.0, *) {
            closeButton.backgroundColor = .systemRed
        } else {
            closeButton.backgroundColor = UIColor(red: 1.0, green: 59.0/255.0, blue: 48.0/255.0, alpha: 1.0)
        }
        closeButton.setTitleColor(.white, for: .normal)
        closeButton.layer.cornerRadius = 8
        closeButton.addTarget(self, action: #selector(closeButtonTapped), for: .touchUpInside)
        closeButton.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(closeButton)

        setupConstraints()
    }

    private func setupConstraints() {
        NSLayoutConstraint.activate([
            // 用户信息标签
            userInfoLabel.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 50),
            userInfoLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
            userInfoLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20),

            // 打开页面B按钮
            openPageBButton.topAnchor.constraint(equalTo: userInfoLabel.bottomAnchor, constant: 50),
            openPageBButton.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            openPageBButton.widthAnchor.constraint(equalToConstant: 200),
            openPageBButton.heightAnchor.constraint(equalToConstant: 44),

            // 关闭按钮
            closeButton.topAnchor.constraint(equalTo: openPageBButton.bottomAnchor, constant: 30),
            closeButton.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            closeButton.widthAnchor.constraint(equalToConstant: 200),
            closeButton.heightAnchor.constraint(equalToConstant: 44)
        ])
    }

    private func displayUserInfo() {
        let infoText = """
        接收到的用户信息：

        姓名: \(userInfo["name"] ?? "未知")
        邮箱: \(userInfo["email"] ?? "未知")
        年龄: \(userInfo["age"] ?? "未知")
        时间戳: \(userInfo["timestamp"] ?? "未知")
        """

        userInfoLabel.text = infoText
        print("📱 页面A显示用户信息: \(userInfo)")
    }

    @objc private func openPageBButtonTapped() {
        print("📱 页面A准备打开页面B")

        // 准备传递给页面B的参数
        let paramsForPageB: [String: Any] = [
            "fromPage": "PageA",
            "userInfo": userInfo,
            "timestamp": Date().timeIntervalSince1970,
            "message": "这是从页面A传递过来的数据"
        ]

        // 创建页面B
        let pageB = PageBViewController()
        pageB.params = paramsForPageB


        // 推送到页面B
        navigationController?.pushViewController(pageB, animated: true)
    }

    @objc private func backButtonTapped() {
        print("📱 页面A返回按钮被点击")

        // 返回数据给Flutter
        //        let returnData: [String: Any] = [
        //            "page": "PageA",
        //            "action": "back_button_tapped",
        //            "userInfo": userInfo,
        //            "timestamp": Date().timeIntervalSince1970,
        //            "message": "用户点击了返回按钮"
        //        ]




        dismiss(animated: true)
    }

    @objc private func closeButtonTapped() {
        print("📱 页面A关闭")

        // 返回数据给Flutter
        //        let returnData: [String: Any] = [
        //            "page": "PageA",
        //            "action": "closed",
        //            "userInfo": userInfo,
        //            "timestamp": Date().timeIntervalSince1970
        //        ]


        dismiss(animated: true)
    }

    // MARK: - PageCallbackDelegate
//    func pageDidClose(with data: [String: Any]) {
//        print("📱 页面A收到页面B回调: \(data)")
//
//    }
}
